/*
 * DictionaryTermsFile.cpp
 *
 *  Created on: Oct 12, 2012
 *      Author: m
 */

#include "DictionaryTermsFile.h"

using namespace physical;

const openmode DictionaryTermsFile::defaulOpenmode = std::ios_base::in
        | std::ios_base::out | std::ios_base::app;

DictionaryTermsFile::DictionaryTermsFile( size_t readBufferSize, size_t writeBufferSize, bool serializeRandomKey ) :
    m_serializer( serializeRandomKey? (DictionaryTermSerializer*) new DictionaryTermLongSerializer() : (DictionaryTermSerializer*) new DictionaryTermShortSerializer() ),
    m_registersFile( m_serializer->getSerializationLength() , (const char*)NULL, defaulOpenmode, readBufferSize, writeBufferSize )
{
}

DictionaryTermsFile::DictionaryTermsFile( const char fileName[], openmode mode, size_t readBufferSize, size_t writeBufferSize, bool serializeRandomKey ) :
            m_serializer( serializeRandomKey? (DictionaryTermSerializer*) new DictionaryTermLongSerializer() : (DictionaryTermSerializer*) new DictionaryTermShortSerializer() ),
    m_registersFile( m_serializer->getSerializationLength() , fileName, mode, readBufferSize, writeBufferSize )
{
}

DictionaryTermsFile::~DictionaryTermsFile()
{
}

std::shared_ptr<DictionaryTerm> DictionaryTermsFile::get()
{
    size_t blockSize = m_serializer->getSerializationLength();

    UP_byteStream block( new byte[ blockSize ] );

    m_registersFile.readRegister( block.get() );

    return m_serializer->deserialize( block.get() );
}

void DictionaryTermsFile::put( DictionaryTerm* newTerm )
{
    UP_byteStream serialization = m_serializer->serialize( newTerm );

    m_registersFile.writeRegister( serialization.get() );
}

bool DictionaryTermsFile::hasNext()
{
    return !m_registersFile.eof();
}

void DictionaryTermsFile::open( const char filename[], openmode mode )
{
    m_registersFile.open( filename, mode );
}

void DictionaryTermsFile::close()
{
    m_registersFile.close();
}
